package com.example.myapplication01.chapter09;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication01.R;
import com.example.myapplication01.chapter09.adapter.PlanetBaseAdapter;
import com.example.myapplication01.chapter09.entity.Planet;

import java.util.List;

class Utils {
    // 根据手机的分辨率从 dp 的单位 转成为 px(像素)
    public static int dip2px(Context context, float dpValue) {
        // 获取当前手机的像素密度（1个dp对应几个px）
        float scale = context.getResources().getDisplayMetrics().density;
        // 四舍五入取整
        return (int) (dpValue * scale + 0.5f);
    }

}
public class ListViewActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener {

    private List<Planet> planetList;
    private CheckBox ck_diviver;
    private CheckBox ck_selector;
    private ListView lv_planet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
        lv_planet = findViewById(R.id.lv_planet);
        planetList = Planet.getDefaultList();
        PlanetBaseAdapter adapter = new PlanetBaseAdapter(this, planetList);
        lv_planet.setAdapter(adapter);

        lv_planet.setOnItemClickListener(this);

        ck_diviver = findViewById(R.id.ck_divider);
        ck_diviver.setOnCheckedChangeListener(this);
        ck_selector = findViewById(R.id.ck_selector);
        ck_selector.setOnCheckedChangeListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this,"您选择的是：" + planetList.get(position).name,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // 修改为if-else结构的完整代码
        if (buttonView.getId()  == R.id.ck_divider)  {
            // 显示/隐藏分隔线逻辑
            if (ck_diviver.isChecked())  {
                Drawable drawable = getResources().getDrawable(R.color.black,  getTheme());
                lv_planet.setDivider(drawable);
                lv_planet.setDividerHeight(Utils.dip2px(this,  1));
            } else {
                lv_planet.setDivider(null);
                lv_planet.setDividerHeight(0);
            }
        } else if (buttonView.getId()  == R.id.ck_selector)  {
            // 显示/隐藏按压背景逻辑
            if (ck_selector.isChecked())  {
                lv_planet.setSelector(R.drawable.list_selector);
            } else {
                Drawable drawable = getResources().getDrawable(R.color.transparent,  getTheme());
                lv_planet.setSelector(drawable);
            }
        }
    }
}